<?php
namespace app\im\controller;
use app\Common\LongbingServiceNotice;
use app\Common\service\LongbingUserInfoService;
use app\im\service\ImService;
use longbingcore\tools\LongbingStr;
use longbingcore\tools\LongbingTime;
use think\App;


class MessageHandlerV2  extends  BaseMessage
{
    //连接客户端ID
    protected $connect_name = 'longbing_im_connect_';
    //链接对应的用户ID
    protected $connect_user_name = 'longbing_im_connect_user';

    //房间ID
    protected $chat_name    = 'longbing_chat_';

    protected $uniacid_wss = 'wss';

    protected $noLogin = ['code' => 401, 'error' => '请登录系统!'] ;

    //发送消息
    public function sendMessage($server ,$client_id ,$data)
    {

        //检查登录
        $user_id = $this->checkLogin($server ,$client_id ,$data);
        if(!$user_id){
            return $this->sendLogin($server , $client_id ) ;
        }


        $uniacid = $data['data']['uniacid'];
        $target_id = $data['data']['target_id']; //接收消息用户id
        $content = $data['data']['content'];


        if( isset($data['data']['id']) && $data['data']['id'] > 0 ) {  //

            $message = $data['data'] ;
            $message_type = $data['data']['message_type'];
        }else{

            $chat_id = ImService::getChatId($uniacid, $user_id, $target_id);
            $message_type = $data['data']['type'];
            $message['message_type'] = $message_type; //
            $message['status'] = 1; //消息状态  1=>未读消息 2=>已读 3=>已撤销 4=>已删除
            $message['user_id'] = $user_id;     //发送消息用户id
            $message['target_id'] = $target_id; //接收消息用户id
            $message['content'] = $content; // 消息内容
            $message['uniacid'] = $uniacid;     //平台ID
            $message['chat_id'] = $chat_id; // 房间ID
            $message['create_time'] = time();
            $message['update_time'] = time();


            ImService::addMessage($message);
        }


        $pushTargetClientId =  intval( $this->getClientIdByUserId($target_id) ) ;

        //客户在线
        if($pushTargetClientId){

            $this->sendServerMsg($server , $pushTargetClientId , 'getNewMessage' ,true,'', $message );
            $this->getUnReadMessageCount($server , $pushTargetClientId , ['data'=>['user_id' => $target_id ] ] );
            $this->getCustomerUnReadMessageCount($server , $pushTargetClientId , ['data'=>['user_id' => $target_id   ,'target_id' =>  $user_id  ] ] );

        }else{
            //发送服务通知给客户
            //员工姓名,必须为中文,不能带有数字和符号
            //$name = LongbingUserInfoService::getNameByUserId($user_id);
            //ImService::sendTmplMsg($uniacid,$target_id,[ $name ,  '有未读私信'  , LongbingTime::getChinaNowTime()]  , 'pages/user/home'  );
        }



        $this->sendServerMsg($server , $client_id , 'sendMessage' ,true,'', $message );
        $this->getUnReadMessageCount($server , $client_id , ['data'=>['user_id'  => $user_id ] ] );

        //给员工发通知消息

        //$note = new LongbingServiceNotice($uniacid);
        //$note->sendImMessageServiceNoticeToStaff($target_id , $content) ;

    }

    //获取未读消息总数
    public function getUnReadMessageCount($server ,$client_id ,$data)
    {
        $user_id =  $data['data']['user_id'] ;
        $count = ImService::getUnReadMessageCount($user_id);

        $this->sendServerMsg($server ,$client_id , 'getUnReadMessageCount' , true,'', ['count' => $count ] ) ;
    }

    //查询目标客户,给我发送的消息数量
    public function getCustomerUnReadMessageCount($server ,$client_id ,$data)
    {

        if (isset($data['data']['target_id']) && isset($data['data']['user_id'])) {

            $user_id = $data['data']['user_id'];
            $target_id = $data['data']['target_id'];

            $count = ImService::getUnReadMessageCountByUserIdAndTargetId( $target_id ,  $user_id);

            $this->sendServerMsg($server, $client_id, 'getCustomerUnReadMessageCount', true, '', ['count' => $count,  'user_id' =>  $user_id  , 'target_id' =>  $target_id ]);

        }
    }


    //登陆
    public function login($server ,$client_id ,$data)
    {

        //登录失败
        $user_id = $this->checkLogin($server ,$client_id ,$data);
        if(!$user_id){
            return $this->sendLogin($server , $client_id ) ;
        }

        $this->updateClentAndUserIdCache($client_id , $user_id);

        $this->sendServerMsg($server ,$client_id , 'login' , true  ) ;

        //用户登录成功,给客户发未读消息数量
        $this->getUnReadMessageCount($server , $client_id , ['data'=>['user_id'  => $user_id ] ] );

    }


    //检查登录
    public function checkLogin( $server ,$client_id ,$data ){

        if(isset($data['data']['token'])){

            $token = $data['data']['token'];
            $uniacid = $data['data']['uniacid'] ;
            $user = getCache($token , $uniacid );

            if(empty($user)){
                return false ;
            }

            return  $user['id'] ;

        }else{
            echo json_encode($data);
        }

        return false ;

    }

    //发送登录提示消息信息
    public function sendLogin( $server ,$client_id ){

        $this->sendServerMsg($server, $client_id ,'login',false,'',$this->noLogin);

    }


    //更新缓存客户和用户ID
    public function updateClentAndUserIdCache($client_id , $user_id){
        //缓存客户端对应的用户ID
        $key = $this->connect_name . $client_id;
        setCache ( $key, $user_id, 3600, $this->uniacid_wss );

        //缓存用户登录对应的客户端ID
        $key = $this->connect_user_name . $user_id;
        setCache ( $key, $client_id, 3600, $this->uniacid_wss );
    }

    //根据用户ID获取 $client_id
    public function getClientIdByUserId($userId){

        $key = $this->connect_user_name . $userId;
        $client_id = getCache( $key ,  $this->uniacid_wss ) ;

        return $client_id;
    }

    //退出
    public function logout($client_id)
    {
        $key = $this->connect_name . $client_id;
        $user_id = getCache( $key ,  $this->uniacid_wss ) ;

        //删除客户对应的用户ID
        delCache($key ,$this->uniacid_wss);

        //删除用户对应的客户ID
        $key = $this->connect_user_name . $user_id;
        delCache($key ,$this->uniacid_wss);

    }


    //检查链接是否正常
    public function checkWs($server ,$client_id ,$data)
    {

        //检查登录
        $user_id = $this->checkLogin($server ,$client_id ,$data);
        if(!$user_id){
            return $this->sendLogin($server , $client_id ) ;
        }
        $this->updateClentAndUserIdCache($client_id , $user_id) ;

        $this->sendServerMsg($server, $client_id ,'checkWsOk');

    }
    
}
